<template>
  <el-dialog
    :title="_transitionLanguages('button', 'permissionSetting')"
    v-model="dialogVisible"
    width="800px"
    top="2vh"
    :destroy-on-close="true"
    draggable
    :close-on-click-modal="false"
    @close="$emit('update:visible', false)"
  >
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane :label="_transitionLanguages('title', 'menusOperationAuthority')" name="first">
        <el-table
          v-loading="dataGrid.loading"
          :data="dataGrid.data"
          highlight-current-row
          :span-method="objectSpanMethod"
          height="500"
          border
        >
          <el-table-column prop="firstMenu" label="菜单" width="150">
            <template #default="{ row }">
              <el-checkbox v-model="row.checkedFirstMenu" :label="row.description" @change="changeFirstMenu(row)" />
            </template>
          </el-table-column>

          <el-table-column prop="operateList" :label="_transitionLanguages('table', 'operation')">
            <template #default="{ row }">
              <span v-for="(operate, operateIndex) in row.operateList" :key="operateIndex" style="margin-right: 10px">
                <el-checkbox
                  v-if="operate.description"
                  v-model="operate.checked"
                  :label="operate.description"
                  @change="changeOperateBtn(row)"
                />
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ _transitionLanguages('button', 'cancel') }}</el-button>
        <el-button type="primary" @click="saveOperateMenu">
          {{ _transitionLanguages('button', 'confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
// roleMenuSave
import type { TableColumnCtx } from 'element-plus';
import { Role } from '@/api/interface/index';

interface SpanMethodProps {
  row: Role.Menu;
  column: TableColumnCtx<Role.Menu>;
  rowIndex: number;
  columnIndex: number;
}

interface OpPermProps {
  visible: boolean;
  roleId: number;
}

interface DataGridProps {
  loading: boolean;
  data: Role.Menu[];
}

const $emit = defineEmits(['update:visible']);

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<OpPermProps>(), {
  visible: false,
  roleId: -1
});
let dialogVisible = ref(props.visible);

let dataGrid = ref<DataGridProps>({
  loading: false,
  data: []
});

watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    if (val) {
      init();
    }
  }
);
watch(
  () => dialogVisible.value,
  val => {
    $emit('update:visible', val);
  }
);

// 语言转换
const _transitionLanguages = (v: string, l: string): string => {
  return transitionLanguages(v, l);
};

// 获取菜单列表
const init = () => {
  const params = {
    roleId: props.roleId
  };
  dataGrid.value.loading = true;
  rolePermissionListByRole(params).then(data => {
    dataGrid.value.loading = false;
    dataGrid.value.data = data;

    dataGrid.value.data.forEach((v: any) => {
      const { choose, subList } = v;
      let children = subList || [];
      v.checkedFirstMenu = !!choose;
      v.firstMenu = v.id;
      v.operateList = children.map(item => {
        return {
          ...item,
          checked: !!item.choose,
          firstMenu: v.id
        };
      });
    });
    console.log(dataGrid.value.data, 'dataGrid.value.data');

    tableMergeColumn(dataGrid.value.data, 'firstMenu');
  });
};

const activeName = ref('first');

const objectSpanMethod = ({ columnIndex, row }: SpanMethodProps) => {
  if (columnIndex === 0) {
    return {
      rowspan: row.rowSpan,
      colspan: 1
    };
  }
};

// 设置保存菜单的参数
const setSaveParams = (): Role.ReqRoleMenuSave => {
  const permissionIds = [];
  dataGrid.value.data.forEach(item => {
    const { checkedFirstMenu } = item;
    if (checkedFirstMenu) {
      permissionIds.push(item.id);
    }
    item.operateList.forEach(son => {
      const { checked } = son;
      if (checked) {
        permissionIds.push(son.id);
      }
    });
  });

  return {
    roleId: props.roleId,
    permissionIds: permissionIds.join(',')
  };
};

// 保存操作的菜单
const saveOperateMenu = async () => {
  const data = setSaveParams();
  await rolePermissionAdd(data);
  $emit('update:visible', false);
  elMessage();
};

// // 一级菜单值变化
const changeFirstMenu = (item: Role.Menu) => {
  const { checkedFirstMenu } = item || {};
  item.operateList.forEach(son => {
    // 三级菜单跟随变化
    son.checked = checkedFirstMenu;
  });
  // item.checkedFirstMenu = !item.checkedFirstMenu;
};

// 对操作栏进行修改
const changeOperateBtn = (item: Role.Menu) => {
  const isCheckedList = item.operateList.filter(son => son.checked);

  // 是否有操作按钮 一个时对2级菜单进行确定  确保有对应2级菜单权限
  if (isCheckedList.length === 1) {
    item.checkedFirstMenu = true;
  }
};
</script>
